package com.hrbxlh.actionImpl;

import com.google.common.base.Function;
import com.hrbxlh.dao.CoursePowerDao;
import com.hrbxlh.util.MapUtils;
import com.hrbxlh.util.pageUtil;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/4.
 */
@Component("coursePowerActionImpl")
@Transactional
public class CoursePowerActionImpl {
    @Resource(name = "coursePowerDao")
    private CoursePowerDao coursePowerDao;

    org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(CoursePowerActionImpl.class.getName());


    /**
     * @description 能力管理列表  分页
     * @param Map<String,Object> paramMap
     * @return List
     * @throws Exception
     */
    public Map<String,Object> getCoursePowerList(Map<String, Object> paramMap) throws Exception{

        Map<String, Object> resultMap = new HashMap<String,Object>();
        try{
           /* int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
            int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
            int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
            paramMap.put("startNum", startNum);*/
            //获取能力列表信息
            List<Map<String, Object>> powerList = coursePowerDao.getCoursePowerDetail(paramMap);
            //获取列表信息
            List<Map<String, Object>> coursePowerList = coursePowerDao.getCoursePowerList(paramMap);
            //循环集合将能力对应的集合放到一起
            for(int i=0;i<powerList.size();i++){
                List<Map<String,Object>> courseList = new ArrayList<>();
                for (int j=0;j<coursePowerList.size();j++){
                    if(Integer.valueOf(String.valueOf(powerList.get(i).get("powerId")))==Integer.valueOf(String.valueOf(coursePowerList.get(j).get("powerId")))){
                        Map<String,Object> courseMap = new HashMap<>();
                        if(coursePowerList.get(j).get("courseId")!=null){
                            courseMap.put("courseId",coursePowerList.get(j).get("courseId"));
                            courseMap.put("courseName",coursePowerList.get(j).get("courseName"));
                            courseMap.put("width",coursePowerList.get(j).get("width"));
                            courseList.add(courseMap);
                        }
                    }
                }
                powerList.get(i).put("courseList",courseList);
            }
            resultMap.put("coursePowerList", powerList);
            resultMap.put("pageNow", 1);
            //获取全部页数
           /* paramMap.put("pageNow", 0);
            paramMap.put("startNum", 0);
            List<Map<String, Object>> allList = coursePowerDao.getCoursePowerList(paramMap);
            int totalPage = pageUtil.getTotalPage(allList, pageSize);*/
            resultMap.put("totalPage", 1);
        }catch(Exception e){
            logger.error("能力管理异常getCoursePowerList", e);
            throw e;
        }
        return resultMap;
    }

    /**
     * 将集合变成map
     */
   /* public Map<String, Map<String, Object>> returnMap(List<Map<String,Object>> paramList,String key){
        Map<String , Map<String, Object>> map = MapUtils.transform(paramList, new Function<Map<String, Object>,String>() {
            @Nullable
            public String apply(@Nullable Map<String, Object> input) {
               *//* Joiner j = Joiner.on("_");
                j.join(String.valueOf(input.get("stuorteaId")),String.valueOf(input.get("courseId")));*//*
                String str = String.valueOf(String.valueOf(input.get(key)));
                return str;
            }
        });
        return map;
    }*/

    /**
     * 添加能力数据
     * @param response
     * @param jsonStr
     */
    public Map<String, Object> addCousrPower(Map<String, Object> paramMap) throws Exception {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean result = false;
        String failMsg = "";
        int powerId = 0;
        try {
            List<Map<String,Object>> powerList = (List<Map<String, Object>>) paramMap.get("powerList");
            for (int i=0;i<powerList.size();i++){
                List<Map<String, Object>> coursePowerList = coursePowerDao.getCoursePowerByName(paramMap);
                //判断能力名重复
                if(coursePowerList != null && coursePowerList.size() != 0){
                    failMsg = coursePowerList.get(0).get("powerName")+"能力数据名称已存在";
                    resultMap.put("failMsg", failMsg);
                    resultMap.put("result", false);
                    return resultMap;
                }else{
                    if(Integer.parseInt(String.valueOf(powerList.get(i).get("powerId")))==0){
                        //添加能力
                        coursePowerDao.addCousrPower(powerList.get(i));
                        powerId = Integer.parseInt(String.valueOf(powerList.get(i).get("powerId")));
                        List<Map<String,Object>> relCourseList = (List<Map<String,Object>>)powerList.get(i).get("relCourseList");
                        if(relCourseList!=null&&relCourseList.size()!=0){
                            //将能力与课程的关联插入表中
                            paramMap.put("powerId",powerId);
                            paramMap.put("relCourseList",relCourseList);
                            coursePowerDao.addrelCoPo(paramMap);
                        }
                    }else{
                        //修改
                        powerId = Integer.parseInt(String.valueOf(powerList.get(i).get("powerId")));
                        coursePowerDao.saveCoursePower(powerList.get(i));
                    }

                    resultMap.put("failMsg", "");
                    resultMap.put("powerId",powerId);
                    result = true;
                }
            }
            if(!result){
                resultMap.put("failMsg", failMsg);
            }
            resultMap.put("result", result);
            logger.info("添加能力数据，参数为："+paramMap.toString());
        } catch (Exception e) {
            logger.error("添加能力数据异常addCousrPower", e);
            throw e;
        }
        return resultMap;
    }

    /**
     * 添加课程权重
     * @param response
     * @param jsonStr
     */
    public Map<String, Object> addCourseWidth(Map<String, Object> paramMap) throws Exception {

        Map<String, Object> resultMap = new HashMap<String, Object>();

        try {
            //获取所有能力值对应课程的课程类型
            List<Map<String,Object>> courseTypeList = coursePowerDao.getAllCourseTypeList(paramMap);
            //获取所有能力值以及对应的课程
            List<Map<String,Object>> cousePowerList = coursePowerDao.getAllReCoursePowerList(paramMap);
            if((courseTypeList!=null&&courseTypeList.size()!=0)&&(cousePowerList!=null&&cousePowerList.size()!=0)){
                //根据课程类型设置能力对应课程的权重
                for(int i=0;i<cousePowerList.size();i++){
                    //如果以后改成一个课对应一个实验、考试、作业权重时用
                    /*for(int j=0;j<courseTypeList.size();j++){
                        if(Integer.parseInt(String.valueOf(cousePowerList.get(i).get("courseId")))==Integer.parseInt(String.valueOf(courseTypeList.get(j).get("courseId")))){
                            //判断当前课程是是什么课程类型
                            if(Integer.parseInt(String.valueOf(courseTypeList.get(j).get("addTestMark")))==1){
                                //实验类型
                                cousePowerList.get(i).put("homeworkWidth",0);
                                cousePowerList.get(i).put("expreWidth",paramMap.get("expreWidth"));
                                cousePowerList.get(i).put("examWidth",paramMap.get("examWidth"));

                            } if(Integer.parseInt(String.valueOf(courseTypeList.get(j).get("addTestMark")))==2){
                                //理论类型
                                cousePowerList.get(i).put("homeworkWidth",paramMap.get("homeworkWidth"));
                                cousePowerList.get(i).put("expreWidth",0);
                                cousePowerList.get(i).put("examWidth",paramMap.get("examWidth"));
                            } if(Integer.parseInt(String.valueOf(courseTypeList.get(j).get("addTestMark")))==3){
                                //实验+理论类型
                                cousePowerList.get(i).put("homeworkWidth",paramMap.get("homeworkWidth"));
                                cousePowerList.get(i).put("expreWidth",paramMap.get("expreWidth"));
                                cousePowerList.get(i).put("examWidth",paramMap.get("examWidth"));
                            }
                            break;
                        }
                    }*/
                    cousePowerList.get(i).put("homeworkWidth",paramMap.get("homeworkWidth"));
                    cousePowerList.get(i).put("expreWidth",paramMap.get("expreWidth"));
                    cousePowerList.get(i).put("examWidth",paramMap.get("examWidth"));
                }
                paramMap.put("relCourseList",cousePowerList);
                coursePowerDao.updateRelCoPo(paramMap);
            }else{
                //说明还没有能力只是单纯的添加课程模块的权重（现在是全部课程都是一个）
                //查询是否已经有数据
               Map<String,Object> cousrWidthMap = coursePowerDao.getCourseWidth();
               if(cousrWidthMap!=null&&cousrWidthMap.size()!=0){
                   //更新
                   coursePowerDao.updateOnlyCourseWidth(paramMap);
               }else{
                   //添加
                   coursePowerDao.addOnlyCourseWidth(paramMap);
               }

            }
            resultMap.put("result",true);
            resultMap.put("failMsg","");
            logger.info("添加课程权重，参数为："+paramMap.toString());
        } catch (Exception e) {
            resultMap.put("result",false);
            resultMap.put("failMsg","添加课程权重数据异常");
            logger.error("添加课程权重数据异常addCourseWidth", e);
            throw e;
        }
        return resultMap;
    }

    /**
     * @description 查询某能力的详细信息
     * @param 地点id
     * @return List
     * @throws Exception
     */
    public Map<String,Object> getCoursePowerDetail(Map<String, Object> paramMap) throws Exception{

        Map<String, Object> resultMap = new HashMap<String,Object>();
        List<Map<String, Object>> coursePowerList = new ArrayList<>();
        try{
            coursePowerList = coursePowerDao.getCoursePowerDetail(paramMap);
            resultMap = coursePowerList.get(0);
            //查询关联信息
            List<Map<String,Object>> relCoPoList = coursePowerDao.getrelCoPoListByPowerId(paramMap);
            resultMap.put("relCoPoList",relCoPoList);
        }catch(Exception e){
            logger.error("查询某地点的详细信息异常getSiteDetail", e);
            throw e;
        }
        return resultMap;
    }

    /**
     * @description 修改能力数据
     * @param  paramMap  能力名称
     * @return Map<String, String> result true成功，false失败 errorMsg错误信息
     * @throws Exception
     */
    public Map<String, Object> saveCoursePower(Map<String, Object> paramMap) throws Exception {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean result = false;
        String failMsg = "";
        try {
            List<Map<String,Object>> powerList = (List<Map<String, Object>>) paramMap.get("powerList");
            //通过能力Id查询能力关联表中实验、考试、作业的权重
            Map<String,Object> recopoMap = coursePowerDao.getCourseWidth();
            float expreWidth = 0;
            float homeworkWidth = 0;
            float examWidth = 0;
            if(recopoMap!=null&&recopoMap.size()!=0){
                expreWidth = Float.parseFloat(String.valueOf(recopoMap.get("expreWidth")));
                homeworkWidth = Float.parseFloat(String.valueOf(recopoMap.get("homeworkWidth")));
                examWidth = Float.parseFloat(String.valueOf(recopoMap.get("examWidth"))) ;
            }
            for(int i=0;i<powerList.size();i++){
                paramMap.put("powerId",powerList.get(i).get("powerId"));
                //增加的课程关联集合
                List<Map<String,Object>> addRelCourseList = (List<Map<String, Object>>) powerList.get(i).get("addRelCourseList");
                //删除的课程关联集合
                List<Map<String,Object>> delRelCourseList = (List<Map<String, Object>>) powerList.get(i).get("delRelCourseList");

                List<Map<String, Object>> coursePowerList = coursePowerDao.getCoursePowerByName(paramMap);
                //判断能力名重复
                if(coursePowerList != null && coursePowerList.size() != 0){
                    failMsg = coursePowerList.get(i).get("powerName")+"能力数据名称已存在";
                    resultMap.put("failMsg", failMsg);
                    resultMap.put("result", false);
                    return resultMap;
                }else{
                    //修改能力
                    coursePowerDao.saveCoursePower(powerList.get(i));
                }
                if(delRelCourseList!=null&&delRelCourseList.size()!=0){
                    //删除relcopo
                    paramMap.put("delRelCourseList",delRelCourseList);
                    List<String> list = new ArrayList<>();
                    list.add(String.valueOf(powerList.get(i).get("powerId")));
                    paramMap.put("list",list);
                    coursePowerDao.delRelCoPoByPowerAndCoureseList(paramMap);
                }
                if(addRelCourseList!=null&&addRelCourseList.size()!=0){
                    //判断要插入的课程集合中是否存在重复
                    boolean repeatFlag = getRepateList(addRelCourseList);
                    if(!repeatFlag){
                        result = false;
                        resultMap.put("result", result);
                        resultMap.put("failMsg", "同一能力中有重复课程");
                        return resultMap;
                    }

                    //将这个能力对应的关联关系清空
                    coursePowerDao.delRelCoPoByPowerId(paramMap);
                    //将实验、考试、作业的权重加入到集合中
                    for(int j=0;j<addRelCourseList.size();j++){
                        addRelCourseList.get(j).put("expreWidth",expreWidth);
                        addRelCourseList.get(j).put("homeworkWidth",homeworkWidth);
                        addRelCourseList.get(j).put("examWidth",examWidth);
                    }
                    //将能力与课程的关联插入表中
                    paramMap.put("relCourseList",addRelCourseList);
                    coursePowerDao.addrelCoPoTwo(paramMap);
                }
                result = true;
                resultMap.put("failMsg", "");
            }
            resultMap.put("result", result);
        } catch (Exception e) {
            logger.error("修改能力数据异常saveCoursePower", e);
            throw e;
        }
        return resultMap;
    }

    /**
     * 判断集合中是否存在重复
     * return false(重复) true(不重复)
     */
    private boolean getRepateList(List<Map<String,Object>> addRelCourseList){
        for(int i=0;i<addRelCourseList.size();i++){
            for (int  j  =  addRelCourseList.size()  -   1 ; j  >  i; j --){
                if(Integer.parseInt(String.valueOf(addRelCourseList.get(i).get("courseId")))==Integer.parseInt(String.valueOf(addRelCourseList.get(j).get("courseId")))){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * @description 删除能力
     * @param Map<String,Object> paramMap
     * @return Map result存成功失败标识   failMsg存错误信息
     * @throws Exception
     */
    public Map<String, Object> delCoursePowers(List<String> list) throws Exception{

        Map<String, Object> result = new HashMap<String, Object>();
        try{
            //删除能力与课程的关联
            coursePowerDao.delRelCoursePowers(list);
            //执行批量删除能力值
            coursePowerDao.delCoursePowers(list);
            result.put("result", true);
            result.put("failMsg", "");
            logger.info("删除能力，参数为："+list.toString());
        }catch(Exception e){
            e.printStackTrace();
            logger.error("删除能力异常delSites", e);
            result.put("result", false);
            result.put("failMsg", "删除失败");
        }
        return result;
    }

    /**
     * @description 获取删除课程的时候是否提示有课程与能力值关联
     * @param Map<String,Object> paramMap
     * @return Map result存成功失败标识   failMsg存错误信息
     * @throws Exception
     */
    public Map<String, Object> getRelCoPoListByCourseList(List<String> list) throws Exception{

        Map<String, Object> result = new HashMap<String, Object>();
        try{
            //获取删除课程的时候是否提示有课程与能力值关联
            List<Map<String,Object>> relcopoList = coursePowerDao.getRelCoPoListByCourseList(list);
            if(relcopoList!=null&&relcopoList.size()!=0){
                result.put("result", "fail");
                result.put("failMsg", "删除课程会导致学生学习报告能力值有改变，请重新设置能力值权重");
                return result;
            }
            result.put("result", "success");
            result.put("failMsg", "");
            logger.info("删除能力，参数为："+list.toString());
        }catch(Exception e){
            e.printStackTrace();
            logger.error("查询课程与能力值关联异常delSites", e);
            result.put("result", "fail");
            result.put("failMsg", "查询课程与能力值关联删除失败");
        }
        return result;
    }


    /**
     * @description 获取课程中各个模块的权重
     * @param
     * @return Map result存成功失败标识   failMsg存错误信息
     * @throws Exception
     */
    public Map<String, Object> getCourseWidth() throws Exception{

        Map<String, Object> result = new HashMap<String, Object>();
        try{
            //获取课程中各个模块的权重
           Map<String,Object> courseWidth = coursePowerDao.getCourseWidth();
            result.put("courseWidth",courseWidth);
            result.put("result", "success");
            result.put("failMsg", "");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("获取课程中各个模块的权重getCourseWidth", e);
            result.put("result", "fail");
            result.put("failMsg", "获取课程中各个模块的权重失败");
        }
        return result;
    }
}
